<?php
namespace app\api\controller\addfile;

use think\Controller;
use think\Request;
use app\common\model\user\User as UserModel;
use app\common\model\factory\Factory as FactoryModel;
use think\Db;
use app\common\model\power\Rolepower;
use app\api\controller\Pub;

class Factory extends Controller
{
    public function initialize()
    {
        parent::initialize();
        $this->is_login();
        Rolepower::powerguard('301002'); // 工厂员工管理权限
    }
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
    // 工厂员工列表
    public function userList(Request $request)
    {
        $pub=new Pub();
        $user_id=$pub->userid();
        $factory_id = Db::name('user_factory')->where('user_id',$user_id)->value('factory_id');
        if (!$factory_id) {
            return json(['code'=>0, 'msg'=>'未绑定工厂']);
        }
        $user_ids = Db::name('user_factory')->where('factory_id', $factory_id)->column('user_id');
        $keyword = $request->get('keyword');
        $query = UserModel::whereIn('UserId', $user_ids);
        if ($keyword) {
            $query->where('Name', 'like', "%$keyword%");
        }
        $list = $query->field('UserId, Iphone, Name, Sex')->select();
        return json(['code'=>1, 'msg'=>'success', 'data'=>$list]);
    }
    
    //添加员工
    public function userAdd(Request $request)
    {
        
        $pub=new Pub();
        $user_id=$pub->userid();

        $factory_id = Db::name('user_factory')->where('user_id', $user_id)->value('factory_id');
        if (!$factory_id) {
            return json(['code'=>0, 'msg'=>'未绑定工厂']);
        }
        $data = $request->post();
        if (empty($data['Iphone']) || empty($data['Name']) || empty($data['sex'])) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        $user = new UserModel();
        $user->Iphone = $data['Iphone'];
        $user->Name = $data['Name'];
        $user->Sex = $data['sex'];
        $user->Role = 302; // 工厂员工
        $user->State = UserModel::STATEOK;
        $user->save();
        Db::name('user_factory')->insert([
            'user_id' => $user->UserId,
            'factory_id' => $factory_id,
        ]);
        return json(['code'=>1, 'msg'=>'添加成功']);
    }

    //员工信息修改
    public function userEdit(Request $request)
    {

        $data = $request->post();
        if (empty($data['UserId']) || empty($data['Name']) || empty($data['Iphone']) || empty($data['sex'])) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }

        $user = UserModel::get($data['UserId']);
        if (!$user) {
            return json(['code'=>0, 'msg'=>'用户不存在']);
        }
        $user->Name = $data['Name'];
        $user->Iphone = $data['Iphone'];
        $user->Sex = $data['sex'];
        $user->save();
        return json(['code'=>1, 'msg'=>'修改成功']);
    }
    public function userDel(Request $request)
    {
        $userId = $request->post('UserId');
        if (empty($userId)) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        Db::startTrans(); // 开启事务
        try {
            // 执行第一个数据库操作
            UserModel::destroy($userId);
            
            // 执行第二个数据库操作
            Db::name('user_factory')->where('user_id', $userId)->delete();
            
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            // 返回错误信息或抛出异常
            return myerr('删除失败');
        }
        return json(['code'=>1, 'msg'=>'删除成功']);
    }
    
    public function orderList(Request $request)
    {
        $loginUser = session('user');
        if (!$loginUser) {
            return json(['code'=>0, 'msg'=>'未登录']);
        }
        $factory_id = Db::name('user_factory')->where('user_id', $loginUser['id'])->value('factory_id');
        if (!$factory_id) {
            return json(['code'=>0, 'msg'=>'未绑定工厂']);
        }
        $orders = Db::name('contract_order')->where('factory_id', $factory_id)->select();
        foreach ($orders as &$order) {
            $order['device'] = Db::name('device')->whereIn('id', json_decode($order['devices_id'], true))->select();
            $order['accessories'] = isset($order['accessories_id']) ? Db::name('accessories')->whereIn('id', json_decode($order['accessories_id'], true))->select() : [];
        }
        return json(['code'=>1, 'msg'=>'success', 'data'=>$orders]);
    }
    public function orderStatusChange(Request $request)
    {
        $loginUser = session('user');
        if (!$loginUser) {
            return json(['code'=>0, 'msg'=>'未登录']);
        }
        $data = $request->post();
        if (empty($data['id']) || empty($data['track_number']) || empty($data['status'])) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        $order = Db::name('contract_order')->where('id', $data['id'])->find();
        if (!$order) {
            return json(['code'=>0, 'msg'=>'订单不存在']);
        }
        Db::name('contract_order')->where('id', $data['id'])->update([
            'track_number' => $data['track_number'],
            'status' => $data['status'],
            'update_time' => time()
        ]);
        return json(['code'=>1, 'msg'=>'修改成功']);
    }
} 